import webview
from flask import Flask, render_template, request
import json
from adb import Adb
from flask_cors import CORS
import os

gui_dir = os.path.join(os.path.dirname(__file__), 'gui')  # development path
static_dir = os.path.join(os.path.dirname(__file__), 'static')  # development path

if not os.path.exists(gui_dir):  # frozen executable path
    gui_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), 'gui')

if not os.path.exists(static_dir):  # frozen executable path
    static_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), 'static')

script = Adb(os.path.join(static_dir, 'adb'))

app = Flask(__name__, template_folder=gui_dir, static_folder=gui_dir, static_url_path='')

CORS(app, resources=r'/*')


def resp(code=0, data={}, message='success'):
    return json.dumps({'code': code, 'data': data, 'message': message}, ensure_ascii=False)


@app.route('/')
def landing():
    return render_template('index.html')


@app.route('/get_dir', methods=['GET'])
def get_dir():
    try:
        dir_path = request.args.get('path')
        is_ok, result_dir = script.get_dir(dir_path)
        if not is_ok:
            return resp(code=500, message=result_dir)
        is_ok, result_files = script.get_file(dir_path)
        if not is_ok:
            return resp(code=500, message=result_files)

        data = []
        count = 0
        for it in result_dir:
            count += 1
            data.append({'id': count, 'is_dir': True, 'name': it})

        for it in result_files:
            count += 1
            data.append({'id': count, 'is_dir': False, 'name': it})

        return resp(code=200, data={'sub_files': data, 'cur_path': dir_path})
    except Exception as e:
        return resp(code=500, message=str(e))


@app.route('/choose_save_dir', methods=['GET'])
def choose_save_dir():
    try:
        save_dir = webview.windows[0].create_file_dialog(webview.FOLDER_DIALOG)
        return resp(200, data={'dir_path': '' if not save_dir else save_dir[0]})
    except Exception as e:
        return resp(500, message=str(e))


@app.route('/download_file', methods=['POST'])
def download_file():
    src_path = request.json.get('src_path')
    dst_path = request.json.get('dst_path')

    if not all([src_path, dst_path]):
        return resp(500, message='无效的路径')

    if not os.path.exists(dst_path):
        return resp(500, message='文件{}不存在'.format(dst_path))

    try:
        is_success, msg = script.download_file(src_path, dst_path)
        return resp(200 if is_success else 500, message=msg)
    except Exception as e:
        return resp(500, message=str(e))


@app.route('/choose_upload_files', methods=['GET'])
def choose_upload_files():
    try:
        files = webview.windows[0].create_file_dialog(webview.OPEN_DIALOG, allow_multiple=True)
        return resp(200, data=[{'file_path': it, 'file_name': os.path.basename(it)} for it in files] if files else [])
    except Exception as e:
        return resp(500, message=str(e))


@app.route('/upload_file', methods=['PUT'])
def upload_file():
    src_path = request.json.get("src_path")
    dst_dir = request.json.get("dst_dir")

    if not all([src_path, dst_dir]):
        return resp(500, message='无效的路径')

    if not os.path.exists(src_path):
        return resp(500, message='文件{}不存在'.format(src_path))

    try:
        is_success, msg = script.upload_file(src_path, dst_dir)
        print(msg)
        return resp(200 if is_success else 500, message=msg)
    except Exception as e:
        return resp(500, message=str(e))


@app.route('/delete_file', methods=['DELETE'])
def delete_file():
    file_path = request.args.get('path')
    if not file_path:
        return resp(500, message='无效的路径')
    try:
        is_success, msg = script.delete_file(file_path)
        return resp(200 if is_success else 500, message=msg)
    except Exception as e:
        return resp(500, message=str(e))
